<%@page import="org.postgresql.util.PSQLException"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html class=""><head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <title>NutriWeb - Praticando alimentação saudável</title>

        <meta class="viewport" name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <!-- Favicon -->
        <link rel="shortcut icon" href="a_data/icone_nutriweb.ico">
        <!-- Font -->
        <link rel="stylesheet" href="arquivos_arquivos/css.css">
        <!-- Plagins CSS -->
        <link rel="stylesheet" href="arquivos_arquivos/buttons.css">
        <link rel="stylesheet" href="arquivos_arquivos/social-icons.css">
        <link rel="stylesheet" href="arquivos_arquivos/font-awesome.css">
        <link rel="stylesheet" href="arquivos_arquivos/bootstrap.css">
        <link rel="stylesheet" href="arquivos_arquivos/jslider.css">
        <link rel="stylesheet" href="arquivos_arquivos/settings.css">
        <link rel="stylesheet" href="arquivos_arquivos/jquery.css">
        <link rel="stylesheet" href="arquivos_arquivos/animate.css">
        <link rel="stylesheet" href="arquivos_arquivos/video-js.css">
        <link rel="stylesheet" href="arquivos_arquivos/morris.css">
        <link rel="stylesheet" href="arquivos_arquivos/royalslider.css">
        <link rel="stylesheet" href="arquivos_arquivos/rs-minimal-white.css">
        <link rel="stylesheet" href="arquivos_arquivos/layerslider.css">
        <link rel="stylesheet" href="arquivos_arquivos/ladda.css">
        <link rel="stylesheet" href="arquivos_arquivos/datepicker.css">
        <link rel="stylesheet" href="arquivos_arquivos/jquery_002.css">
        <!-- Theme CSS -->
        <link rel="stylesheet" href="a_data/style.css">
        <!-- Responsive CSS -->
        <link rel="stylesheet" href="a_data/responsive.css">
        <!-- Custom CSS -->
        <link rel="stylesheet" href="a_data/pages.css">
        <link rel="stylesheet" href="a_data/home-pages-customizer.css">
        <!-- IE Styles-->
        <link rel="stylesheet" href="a_data/ie.css">
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
          <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
              <link rel='stylesheet' href="css/ie/ie8.css">
        <![endif]-->
        <style type="text/css">
            .jqstooltip { position: absolute;left: 0px;top: 0px;visibility: hidden;background: rgb(0, 0, 0) transparent;background-color: rgba(0,0,0,0.6);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";color: white;font: 10px arial, san serif;text-align: left;white-space: nowrap;padding: 5px;border: 1px solid white;z-index: 10000;}.jqsfield { color: white;font: 10px arial, san serif;text-align: left;}</style>
        <style type="text/css">.fancybox-margin{margin-right:19px;}</style>
        <script style="" src="arquivos_arquivos/commonutilstats.js" charset="UTF-8" type="text/javascript"></script>
    </head>
    <body class="fixed-header loaded fixed">    
        <div class="page-box">
            <div class="page-box-content">
                <%@include file="/templates/header.jsp"%>   
                <div class="breadcrumb-box">
                    <div class="container">
                        <ul class="breadcrumb">
                            <li><a href="inicio.jsp">Início</a> </li>
                            <li><a href="#">Alimento</a> </li>
                            <li class="active">Cadastrar</li>
                        </ul>	
                    </div>
                </div>
                <%@include file="/templates/welcome.jsp"%>
                <div class="clearfix"></div>
                <%
                
                    if (session.getAttribute("ic_admin") == null || session.getAttribute("ic_admin").toString().equals("false")) {
                        response.sendRedirect(request.getContextPath() + "/inicio.jsp");
                        return;
                    }
                
                    String error_msg = "";
                    int error = 0;
                    if (request.getParameter("error") != null) {
                        error = Integer.parseInt(request.getParameter("error").toString());
                        switch (error) {
                            case 1:
                                error_msg = " Atenção, já existe um alimento cadastrado com este nome!";
                                break;
                            case 2:
                                error_msg = " Atenção, selecione um grupo alimentar!";
                                break;
                        }
                    }

                    if (request.getParameter("edit") != null) {
                        Long cd = Long.parseLong(request.getParameter("edit"));
                        session.setAttribute("cd_alimento", cd);
                        SQL = "SELECT nm_alimento, cd_grupo, ds_alimento_equivalencia, qt_alimento FROM \"Operacoes\".\"ALIMENTO\" WHERE cd_alimento = " + cd + " ";
                        try {
                            for (Object[] reg : Conexao.getQuery(SQL)) {
                                session.setAttribute("nm_alimento", reg[0].toString());
                                session.setAttribute("cd_grupo", reg[1].toString());
                                session.setAttribute("ds_alimento_equivalencia", reg[2].toString());
                                session.setAttribute("qt_alimento", reg[3].toString());
                            }
                        } catch (Exception e) {
                            out.println("Atenção, " + e.getLocalizedMessage());
                        }
                    }
                %>  
                <section id="main">
                    <header class="page-header">
                        <div class="container">
                            <%
                                if (session.getAttribute("nm_alimento") != null) { %>
                            <h1 class="title">Editar Alimento</h1>
                            <%} else {%>
                            <h1 class="title">Cadastrar Alimento</h1>
                            <%}%>
                        </div>	
                    </header>

                    <div class="container">
                        <div class="panel-group" id="accordion3">

                            <div class="col-sm-6 col-md-6 bottom-padding">
                                <form id="contactform" name="contactform" action="" novalidate="novalidate" class="form-box register-form form-validator bv-form" method="post">
                                    <input type="hidden" name="update"
                                           <% if (session.getAttribute("nm_alimento") != null) { %>
                                           value="yes"
                                           <% } else { %>
                                           value="no"
                                           <%}%>
                                           >
                                    <h3 class="title">                  
                                        <% if (session.getAttribute("nm_alimento") != null) { %>Editar<%} else {%>Cadastrar<%}%>
                                    </h3>                          
                                    <div id="success"></div>
                                    <div class="form-group has-feedback">
                                        <label>Nome: <span class="required" >*</span></label><label style="color:red"><%if (error == 1) {out.print(error_msg);}%></label>
                                        <input class="form-control" type="text" name="txtNome" <% if (session.getAttribute("nm_alimento") != null) { %>Value="<%out.print(session.getAttribute("nm_alimento"));%>"<%}%> 
                                               data-bv-field="nome" data-bv-trigger="keyup" data-bv-notempty-message="Preencha o nome." required="required" maxlength="50">
                                        <i data-bv-icon-for="nome" class="form-control-feedback" style="display: none;"></i>
                                        <small data-bv-result="NOT_VALIDATED" data-bv-for="nome" data-bv-validator="notEmpty" class="help-block" style="display: none;">Preencha o nome.</small> 
                                    </div>
                                        <label>Grupo: <span class="required" >*</span></label><label style="color:red"><%if (error == 2) {out.print(error_msg);}%></label>
                                    <select class="form-control" data-bv-emailaddress-message="Selecione um alimento"
                                            required name="slGrupo" class="form-control" required> <!-- name="selCereal"  -->
                                        <option value="" <% if (session.getAttribute("cd_grupo") == null) { %>selected<%}%>>Selecione um grupo alimentar...</option>
                                        <%
                                            SQL = "SELECT cd_grupo, nm_grupo FROM \"Operacoes\".\"GRUPO\" ORDER BY cd_grupo";
                                            try {
                                                for (Object[] reg : Conexao.getQuery(SQL)) { %>
                                        <option value="<% out.print(reg[0].toString()); %>" <% if (session.getAttribute("cd_grupo") != null && session.getAttribute("cd_grupo").equals(reg[0].toString())) { %>selected<% }%>><% out.print(reg[1].toString()); %></option>
                                        <%
                                                }
                                            } catch (Exception e) {
                                                out.println("Atenção, " + e.getLocalizedMessage());
                                            }
                                        %>              
                                    </select>
                                    <div class="form-group has-feedback">
                                        <label>Quantidade: (em gramas) <span class="required" >*</span></label>
                                        <input class="form-control" type="text" name="txtQtde" oninvalid="InvalidMsg(this);" <% if (session.getAttribute("qt_alimento") != null) { %>Value="<%out.print(session.getAttribute("qt_alimento"));%>"<%}%> 
                                               data-bv-field="qtde" data-bv-trigger="keyup" data-bv-notempty-message="Preencha a quantidade." required="required" maxlength="10">
                                        <i data-bv-icon-for="qtde" class="form-control-feedback" style="display: none;"></i>
                                        <small data-bv-result="NOT_VALIDATED" data-bv-for="qtde" data-bv-validator="notEmpty" class="help-block" style="display: none;">Preencha a quantidade.</small> 
                                    </div>
                                    <div class="form-group has-feedback">                              
                                        <label>Equivalência: (a porção) <span class="required" >*</span></label>
                                        <input class="form-control" type="text" name="txtEquiv" oninvalid="InvalidMsg(this);" <% if (session.getAttribute("ds_alimento_equivalencia") != null) { %>Value="<%out.print(session.getAttribute("ds_alimento_equivalencia"));%>"<%}%> 
                                               data-bv-field="equiv" data-bv-trigger="keyup" data-bv-notempty-message="Preencha a equivalência." required="required" maxlength="50">
                                        <i data-bv-icon-for="equiv" class="form-control-feedback" style="display: none;"></i>
                                        <small data-bv-result="NOT_VALIDATED" data-bv-for="equiv" data-bv-validator="notEmpty" class="help-block" style="display: none;">Preencha a equivalência.</small> 
                                    </div>
                                    <div class="buttons-box clearfix">
                                        <button class="btn btn-default" type="submit" id="submit_btn">                   
                                            <% if (session.getAttribute("nm_alimento") != null) { %>Salvar<%} else {%>Cadastrar<%}%>
                                        </button>
                                        <button class="btn btn-default" type="reset">Limpar</button>
                                        <span class="required"><b>*</b> Campos Obrigatórios</span>
                                    </div><!-- .buttons-box -->

                                    <%
                                        if (session.getAttribute("nm_alimento") != null) {
                                            session.removeAttribute("nm_alimento");
                                            session.removeAttribute("cd_grupo");
                                            session.removeAttribute("qt_alimento");
                                            session.removeAttribute("ds_alimento_equivalencia");
                                        }
                                    %>

                                </form>
                            </div>


                        </div>

                        <%
                            if (request.getParameter("txtNome") != null
                                    && request.getParameter("slGrupo") != null
                                    && request.getParameter("txtQtde") != null
                                    && request.getParameter("txtEquiv") != null
                                    && request.getParameter("slGrupo") != null) {

                                String name = request.getParameter("txtNome");
                                Long group = Long.parseLong(request.getParameter("slGrupo"));

                                if (group.equals((long) 0)) {
                                    response.sendRedirect(request.getContextPath() + "/cadastrar_alimento.jsp?error=2");
                                    return;
                                }

                                Double qt = Double.parseDouble(request.getParameter("txtQtde"));
                                String equiv = request.getParameter("txtEquiv");

                                if (request.getParameter("update") != null && request.getParameter("update").toString().equals("yes")) {
                                    Long cd = Long.parseLong(session.getAttribute("cd_alimento").toString());

                                    Object[] params = new Object[]{name, qt, equiv, group, cd};

                                    SQL = "UPDATE \"Operacoes\".\"ALIMENTO\" SET "
                                            + "nm_alimento= ?, qt_alimento= ?, ds_alimento_equivalencia= ?, cd_grupo= ? WHERE cd_alimento = ? ";
                                    try {
                                        Conexao.executeStatement(SQL, params);
                                        session.removeAttribute("cd_alimento");
                                        response.sendRedirect(request.getContextPath() + "/consultar_alimento.jsp");
                                        return;
                                    } catch (Exception e) {
                                        if (((PSQLException) e).getSQLState().equals("23505")) {
                                            response.sendRedirect(request.getContextPath() + "/cadastrar_alimento.jsp?error=1");
                                            return;
                                        }
                                        //out.println("Atenção, erro ao atualizar " + e.getLocalizedMessage());
                                    }
                                } else {

                                    Object[] params = new Object[]{name, qt, equiv, group};

                                    SQL = "INSERT INTO \"Operacoes\".\"ALIMENTO\" (nm_alimento, qt_alimento, ds_alimento_equivalencia, cd_grupo) "
                                            //+ "VALUES ('" + name + "', " + qt + ", '" + equiv + "', " + group + ")";
                                            + "VALUES (?, ?, ?, ?)";
                                    try {
                                        Conexao.executeStatement(SQL, params);
                                        response.sendRedirect(request.getContextPath() + "/consultar_alimento.jsp");
                                        return;
                                    } catch (Exception e) {
                                        if (((PSQLException) e).getSQLState().equals("23505")) {
                                            response.sendRedirect(request.getContextPath() + "/cadastrar_alimento.jsp?error=1");
                                            return;
                                        }
                                        //out.println("Atenção, erro ao inserir " + e.getLocalizedMessage());
                                    }
                                }
                            }
                        %>
                    </div>
                </section><!-- #main -->

            </div><!-- .page-box-content -->
        </div><!-- .page-box -->
        <%@include file="/templates/footer.jsp"%> 
        <div class="clearfix"></div>

        <script async="" src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/www-widgetapi.js" id="www-widgetapi-script"></script><script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/iframe_api"></script><script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_015.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/bootstrap.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jshashtable-2.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_018.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/tmpl.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_012.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/draggable-0.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_021.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_016.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_022.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_009.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_019.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_011.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_007.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_008.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_005.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/isotope.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_006.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_017.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_020.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_003.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_013.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/SmoothScroll.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/country.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/spin.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/ladda.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/masonry.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/morris.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/raphael.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/video.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/pixastic.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/livicons-1.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/greensock.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/layerslider_002.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/layerslider.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_014.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_004.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/bootstrapValidator.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/bootstrap-datepicker.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_010.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jplayer.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/jquery_002.js"></script>
        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/main.js"></script>


        <script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/js" type="text/javascript"></script><script src="Accordions%20&amp;%20Toggles%20_%20Progressive%20%E2%80%94%20Responsive%20Multipurpose%20HTML%20Template_arquivos/main_002.js"></script></body></html>
